package leeon.bbsbrower.actions;

import ipworks.IPWorksException;

import leeon.bbsbrower.util.HTMLUtil;
import leeon.bbsbrower.util.HTTPBean;

public class BBSMsgAction {
	
	public static final String URL_NEW_MSG = Config.SERVER_URL + Config.SERVER_CGI + "bbsgetmsg";
	
	public static final String URL_ALL_MSG = Config.SERVER_URL + Config.SERVER_CGI + "bbsmsg";
	
	public static final String URL_SEND_MSG = Config.SERVER_URL + Config.SERVER_CGI + "bbssendmsg";
	
	
	/**
	 * 定时刷新获取最新的msg
	 * @return
	 * @throws TooManyListenersException 
	 * @throws IPWorksException 
	 */
	public static String[] getNewMsg() throws IPWorksException {
		HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
		String content = http.get(URL_NEW_MSG);
			
		if (content.indexOf("<bgsound src=/msg.wav>") != -1) {
			String[] re = new String[3];
			//发msg的人
			re[0] = HTMLUtil.findStr(content, "<b>", "</b>");
			//内容
			re[1] = HTMLUtil.findStr(content, "<font class=c37>", "</font>");
			if (re[1] != null) re[1].trim();
			//pid
			re[2] = HTMLUtil.findStr(content, "destpid=", ">");
			return re;
		} else 
			return null;			
	}
	
	/**
	 * 获取所有的msg
	 * @return
	 * @throws TooManyListenersException 
	 * @throws IPWorksException 
	 */
	public static String getAllMsg() throws IPWorksException {
			HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
			String content = http.get(URL_ALL_MSG);
			if (content != null) {
				content = HTMLUtil.findStr(content, "<pre>", "</pre>");
				content = HTMLUtil.removeHtmlTag(content);			
				return content;
			} else 
				return null;
	}
	
	/**
	 * 获取所有的msg,返回发送结果
	 * @return
	 * @throws IPWorksException 
	 * @throws TooManyListenersException 
	 * @throws ContentException 
	 */
	public static void sendMsg(String id, String msg, String pid) throws IPWorksException, ContentException {
			HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
			String url = URL_SEND_MSG + "?";
			url += "destid=" + id + "&";
			url += "msg=" + msg + "&";
			if (pid != null)
				url += "destpid=" + pid;
			else
				url += "destpid=0";
			
			String content = http.get(url);			
			if (content == null || content.indexOf("已经帮您送出消息") == -1)
				throw new ContentException(content);
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {		
	}

}
